﻿using System;
using System.Collections.Generic;
using System.Data;
using System.Data.SqlClient;
using System.Linq;
using System.Text;
using System.Threading.Tasks;

namespace LuDragon.Data.DataHandler
{
    /// <summary>
    /// SQL帮助类
    /// </summary>
    public class SqlHelper
    {
        private static string connectionStr = System.Configuration.ConfigurationManager.ConnectionStrings["DbContext"]?.ToString();

        /// <summary>
        /// SQL查询
        /// </summary>
        /// <param name="sql"></param>
        /// <param name="parameters"></param>
        /// <param name="connectionString"></param>
        /// <returns></returns>
        public static DataSet QueryBySql(string sql, SqlParameter[] parameters = null, string connectionString = null)
        {
            if (string.IsNullOrWhiteSpace(connectionString))
            {
                connectionString = connectionStr;
            }
            using (SqlConnection conn = new SqlConnection(connectionString))
            {
                try
                {
                    SqlCommand cmd = new SqlCommand
                    {
                        CommandText = sql,
                        Connection = conn,
                        CommandType = CommandType.Text
                    };
                    conn.Open();
                    if (parameters != null)
                    {
                        cmd.Parameters.AddRange(parameters);
                    }
                    SqlDataAdapter da = new SqlDataAdapter { SelectCommand = cmd };
                    DataSet ds = new DataSet();
                    da.Fill(ds);
                    conn.Close();
                    return ds;
                }
                catch (Exception ex)
                {
                    throw new Exception(ex.Message, ex);
                }
            }
        }
    }
}
